//
//  VideoViewController.m
//  NeteaseNewsLY
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "VideoViewController.h"
#import "UMSocialSnsService.h"
#import "UMSocialSnsPlatformManager.h"
@interface VideoViewController ()<UITableViewDelegate, UITableViewDataSource, UMSocialUIDelegate>

@property (nonatomic, retain) UITableView *playTableView;
@property (nonatomic, retain)NSMutableArray *dataArr;
@property(nonatomic, retain)MPMoviePlayerViewController *movieView;/** 播放视图*/

@property(nonatomic, retain)NSIndexPath *indexPath;
@property(nonatomic, assign)CGRect selectRect;/**尺寸*/
@property(nonatomic, assign)BOOL isFull;/**全屏*/
@property(nonatomic, strong)UIButton *button;

@property(nonatomic, retain)VideoCell *cell;

@property (nonatomic, retain)UICollectionView *collectionView;
@property (nonatomic, retain)NSMutableArray *headDataArr;
@end

@implementation VideoViewController

- (void)dealloc
{
    [_playTableView release];
    [_dataArr release];
    [_movieView release];
    [_indexPath release];
    [_cell release];
    [_collectionView release];
    [_headDataArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"视频";
    
    //调用系统MPMoviePlayerViewControler的方法 点击满屏播放 再点击回到原来  通过中心点设置
    
    //    @"MPMoviePlayerWillEnterFullscreenNotification" 系统参数 进入全屏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jumpFullScreen) name:@"MPMoviePlayerWillEnterFullscreenNotification" object:nil];
    //跳出全屏
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen) name:@"MPMoviePlayerWillExitFullscreenNotification" object:nil];
    [self headerData];
    //    [self data];
    [self createTableView];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self headerData];
        [self.playTableView.mj_header endRefreshing];
    }];
    self.playTableView.mj_header = header;
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self dataFooter];
        [self.playTableView.mj_footer endRefreshing];
    }];
    self.playTableView.mj_footer = footer;
}

- (void)viewDidAppear:(BOOL)animated
{
    if (!self.isFull) {
        if (self.movieView.view) {
            //移除
            [self.movieView.view removeFromSuperview];
        }
    }
}
#pragma mark - 进入全屏方法实现
- (void)jumpFullScreen
{
    self.isFull = YES;
}
#pragma mark - 退出全屏
- (void)exitFullScreen
{
    self.isFull= NO;
}
#pragma mark - 创建tableView
- (void)createTableView
{
    self.playTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height ) style:UITableViewStylePlain];
    //如果没有设置将返回默认值
    self.playTableView.rowHeight =self.view.frame.size.height  / 2;
    self.playTableView.contentInset = UIEdgeInsetsMake(0, 0, WIDTH * 120, 0);
    self.playTableView.delegate = self;
    self.playTableView.dataSource = self;
    self.playTableView.showsVerticalScrollIndicator = NO;
    self.playTableView.separatorStyle = NO;
    [self.view addSubview:_playTableView];
    [_playTableView release];
    
    //注册cell
    [_playTableView registerClass:[VideoCell class] forCellReuseIdentifier:@"cell"];

    self.playTableView.tableHeaderView = _collectionView;
    
}
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mediaPlaybackStateChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:self.movieView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mediaPlayerPlaybackFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:self.movieView];
    
}
- (void)mediaPlaybackStateChange:(NSNotification *)nsnotification
{
    switch (self.movieView.moviePlayer.playbackState) {
        case MPMoviePlaybackStatePlaying:
            NSLog(@"正在播放");
            break;
        case MPMoviePlaybackStatePaused:
            NSLog(@"暂停播放");
            break;
        case MPMoviePlaybackStateStopped:
            NSLog(@"停止播放");
            break;
        default:
            NSLog(@"播放状态:%li", (long)self.movieView.moviePlayer.playbackState);
            break;
    }
}

- (void)mediaPlayerPlaybackFinished:(NSNotification *)notfication {
    NSLog(@"播放完成.%li", (long)self.movieView.moviePlayer.playbackState);
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}

///处理数据
- (void)headerData
{
    //    [MBProgressHUDManager showHUDtoView:self.view string:@"加载中"];
    NSString *str = @"http://c.m.163.com/nc/video/home/0-10.html";
    [AFHTTPHandler GETWithURL:str completion:^(id result) {
        self.dataArr = [VideoModel modelHandleWithArray:result[@"videoList"]];
        [_playTableView reloadData];
    }];
}
/// 加载数据
- (void)dataFooter
{
    static NSInteger t = 20;
    NSString *str = [NSString stringWithFormat:@"http://c.m.163.com/nc/video/home/%ld-10.html", t];
    [AFHTTPHandler GETWithURL:str completion:^(id result) {
        NSArray *arr = [NSArray array];
        arr = [VideoModel modelHandleWithArray:result[@"videoList"]];
        for (NSInteger i = 0; i < arr.count; i++) {
            [self.dataArr addObject:arr[i]];
        }
        [_playTableView reloadData];
    }];
    t += 10;
}

//cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *vi = _dataArr[indexPath.row];
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [self.cell.cover sd_setImageWithURL:[NSURL URLWithString:vi.cover]];   
    self.cell.title.text = vi.title;
    self.cell.miaoshu.text = vi.desc;
    self.cell.playCount.text = [vi.playCount stringValue];
    self.cell.playTime.text =[NSString stringWithFormat:@"%02d:%02d", [vi.length intValue] / 60, [vi.length intValue]% 60];
    
    //点击cell的颜色
    self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //开启用户交互
    _cell.cover.userInteractionEnabled = YES;
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    //将手势添加在图片上
    [_cell.cover addGestureRecognizer:tap];
    
    //点几下才能触发的方法
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    return self.cell;
}

#pragma mark - 图片点击方法
- (void)tapAction:(UITapGestureRecognizer *)sender
{
    //执行前先清空再播放视频
    if (self.movieView.view) {
        [self.movieView.view removeFromSuperview];
    }
    //获取点击的图片
    UIView *view = sender.view;
    //获取点击的cell
    UITableViewCell *cell = (UITableViewCell *)view.superview.superview;
    //获取点击cell的下标 确定点击的是哪个cell
    self.indexPath = [self.playTableView indexPathForCell:cell];
    //创建一个存放cell的model类
    VideoModel *model = self.dataArr[self.indexPath.row];
    //获取视频网址
    self.movieView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    //位置坐标
    self.movieView.view.frame = CGRectMake(WIDTH * 10, HEIGHT * 10, self.view.frame.size.width - (WIDTH * 20), HEIGHT * 200);
    [self.movieView.moviePlayer setScalingMode:(MPMovieScalingModeAspectFit)];
    [self.movieView.moviePlayer setControlStyle:(MPMovieControlStyleEmbedded)];
    [cell addSubview:self.movieView.view];
    
    //关闭按钮
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.button addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
    [self.button setBackgroundImage:[UIImage imageNamed:@"guanbi"] forState:UIControlStateNormal];
    [self.movieView.view addSubview:self.button];
    //    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.right.equalTo(self.movieView.view).with.offset(-5);
    //        make.top.equalTo(self.movieView.view.mas_top).with.offset(5);
    //        make.width.mas_equalTo(20);
    //        make.height.mas_equalTo(20);
    //    }];
}

#pragma mark - button
- (void)close:(UIButton *)button {
    [self.movieView.moviePlayer stop];
    [self.movieView.moviePlayer pause];
    [self.movieView.view removeFromSuperview];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  HEIGHT * 310;
}
- (void)share:(UIButton *)share
{
    VideoModel *m = _dataArr[_indexPath.row];
    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeVideo url:m.mp4_url];
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56a87642e0f55ae402002a71"
                                      shareText:m.title
                                     shareImage:[UIImage imageNamed:@"icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,nil]
                                       delegate:self];
    
}
- (void)shareValue:(NSInteger *)index
{
//    VideoModel *m = _dataArr[index.row];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
